package com.chen.base.utils.basic;

import cn.hutool.core.date.DatePattern;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author: ~龙~
 * @date: 2023/6/14 16:56
 **/
public class DateExUtil {

    public static String format(String formatType, Date date){
        switch (formatType){
            case "d":
                formatType = DatePattern.NORM_DATE_PATTERN;
                break;
            case "t":
                formatType = DatePattern.NORM_TIME_PATTERN;
                break;
            default:
                formatType = DatePattern.NORM_DATETIME_PATTERN;
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat(formatType);
        return dateFormat.format(date);
    }

    public static String format(String formatType, LocalDateTime dateTime){
        DateTimeFormatter formatter;
        switch (formatType){
            case "d":
                formatter = DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN);
                break;
            case "t":
                formatter = DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN);
                break;
            default:
                formatter = DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN);
        }
        if (dateTime == null){
            dateTime = LocalDateTime.now();
        }
        return dateTime.format(formatter);
    }

    public static Period between(LocalDate start, LocalDate end){
        return Period.between(start,end);
    }

    /** 根据毫秒数优雅显示时间 **/
    public static String format(long milliseconds) {
        long mss = milliseconds / 1000;
        long days = mss / (60 * 60 * 24);
        long hours = (mss % (60 * 60 * 24)) / (60 * 60);
        long minutes = (mss % (60 * 60)) / 60;
        long seconds = mss % 60;
        DecimalFormat format = new DecimalFormat("00");
        StringBuilder str = new StringBuilder();
        if (days > 0){
            str.append(days).append("天");
        }
        if (hours > 0){
            str.append(format.format(hours)).append("时");
        }
        if (minutes > 0){
            str.append(format.format(minutes)).append("分");
        }
        if (seconds > 0){
            str.append(format.format(seconds)).append("秒");
        }
        return str.toString();
    }

}
